/**
 * Created by zhangxiaoyu on 16/12/16.
 */
angular.module("hyt.personCtrl",[])

  .controller('personCtrl', function($scope,$state,$ionicLoading,Storage,$ionicPopup,$ionicHistory,ENV,Version,$timeout,$cordovaFileTransfer,$cordovaFileOpener2,LoadUserDepts,ChangeDept) {
    var userMsg=Storage.get('loginResult');
    var loginMsg=Storage.get('user');
    var download_url;
    $scope.cname=userMsg.rows.cname;
    $scope.mobile=userMsg.rows.username;
    $scope.deptName=userMsg.rows.deptName;
    var loadDepts={
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    LoadUserDepts.getLoadUserDepts(JSON.stringify(loadDepts));
    $scope.$on('LoadUserDepts.Updated', function() {
      $scope.loadDepts=LoadUserDepts.getResult().rows;
    });
    var changeDept={
      deptId:'',
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    $("#changeDept").change(function(e) {
      changeDept.deptId=$("#changeDept").val();
      ChangeDept.getChangeDept(JSON.stringify(changeDept));
    });
    $scope.$on('ChangeDept.Updated', function() {
      var result=ChangeDept.getResult();
      if (result.success){
        $ionicLoading.show({
          noBackdrop: true,
          template: "站点切换成功",
          duration: 1500
        });
        userMsg.rows.deptName=$("#changeDept option:selected").text();
        Storage.set('loginResult',userMsg);
      }
    });
    var version={
      versionno:ENV.version,
      app_type:"1",
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    Version.getVersion(JSON.stringify(version));
    $scope.$on('Version.Updated', function() {
      var result=Version.getResult().rows;
      if (result==undefined){
        $scope.cn=0;
      }else {
        $scope.cn=1;
        download_url=result.DOWNLOAD_URL;
      }
    });
    //检查更新
    $scope.checkAPK=function(){
      if ($scope.cn==0){
        $ionicLoading.show({
          noBackdrop: true,
          template: "当前已是最新版本",
          duration: 1500
        });
      }else if ($scope.cn==1){
        showUpdateConfirm();
      }
    };
    function showUpdateConfirm() {
      var confirmPopup = $ionicPopup.confirm({
        title: '版本升级',
        cancelText: '取消',
        okText: '升级'
      });

      confirmPopup.then(function (res) {
        if (res) {
            $ionicLoading.show({
              template: "已经下载：0%"
            });
            var url = download_url; //可以从服务端获取更新APP的路径
            var targetPath= "file:///storage/sdcard0/hytAndroid/hyt.apk";
            //APP下载存放的路径，可以使用cordova file插件进行相关配置
            var trustHosts = true;
            var options = {};

            $cordovaFileTransfer.download(url,targetPath,options,trustHosts).then(function (result) {
              // 打开下载下来的APP
              $cordovaFileOpener2.open(targetPath, 'application/vnd.android.package-archive'
              ).then(function () {
                // 成功
              }, function (err) {
                // 错误
              });
              $ionicLoading.hide();
            }, function (err) {
              $ionicLoading.show({template: '下载失败！', noBackdrop: true, duration: 2000});
            }, function (progress) {
              //进度，这里使用文字显示下载百分比
              $timeout(function () {
                var downloadProgress = (progress.loaded / progress.total) * 100;
                $ionicLoading.show({
                  template: "已经下载：" + Math.floor(downloadProgress) + "%"
                });
                if (downloadProgress > 99) {
                  $ionicLoading.hide();
                }
              })
            });
        } else {
          // 取消更新
        }
      });
    }
    //退出登录
    $scope.exitLogin=function(){
      var confirmPopup = $ionicPopup.confirm({
        title:'退出当前账号',
        template: '您确定要退出吗？',
        okText:'确定',
        cancelText:'取消'
      });
      confirmPopup.then(function(res) {
        if(res){
          Storage.set('isLogin',0);
          Storage.remove('loginResult');
          $ionicHistory.clearCache();
          $ionicHistory.clearHistory();
          $state.go('login');
        }
        else {
          return false;
        }
      });
    };
  })
  .controller('printSetCtrl', function($scope,$state,$ionicLoading,Storage,getPrinter,savePrinter,$cordovaHdoitBle) {
    var loginMsg=Storage.get('user');
    var userMsg=Storage.get('loginResult');
    var printMsg={
      deptId:userMsg.rows.baseDeptId,
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    getPrinter.getPrintSet(JSON.stringify(printMsg));
    $scope.$on('GetPrint.Updated', function() {
      $scope.prints=getPrinter.getResult().rows;
      if ($scope.prints.shipper_flag==1){
        $scope.prints.shipper_flag=true;
      }else {
        $scope.prints.shipper_flag=false;
      }
      if ($scope.prints.company_flag==1){
        $scope.prints.company_flag=true;
      }else {
        $scope.prints.company_flag=false;
      }
      if ($scope.prints.goods_flag==1){
        $scope.prints.goods_flag=true;
      }else {
        $scope.prints.goods_flag=false;
      }
      //if ($scope.prints.infofee_flag==1){
      //  $scope.prints.infofee_flag=true;
      //}else {
      //  $scope.prints.infofee_flag=false;
      //}
      if ($scope.prints.print_behave!=null){
        $('#print_behave').val($scope.prints.print_behave);
      }
    });

    $scope.savaPrint=function(){
      var prints={
        deptId:userMsg.rows.baseDeptId,
        id:$scope.prints.id,
        shipper_flag:'',
        shipper_pieces:'',
        company_flag:'',
        company_pieces:'',
        goods_flag:'',
        goods_pieces:'',
        //infofee_flag:'',
        print_behave:$('#print_behave option:selected').val(),
        company_name:$scope.prints.company_name,
        phone:$scope.prints.phone,
        remark:$scope.prints.remark,
        userMsg:{
          username:loginMsg.username,
          password:loginMsg.password,
          uuid:loginMsg.uuid
        }
      };
      if ($scope.prints.shipper_flag==true){
        prints.shipper_flag=1;
        prints.shipper_pieces='1';
      }else {
        prints.shipper_flag=0;
        prints.shipper_pieces='0';
      }
      if ($scope.prints.company_flag==true){
        prints.company_flag=1;
        prints.company_pieces='1';
      }else {
        prints.company_flag=0;
        prints.company_pieces='0';
      }
      if ($scope.prints.goods_flag==true){
        prints.goods_flag=1;
        prints.goods_pieces='1';
      }else {
        prints.goods_flag=0;
        prints.goods_pieces='0';
      }
      //if ($scope.prints.infofee_flag==true){
      //  prints.infofee_flag=1;
      //}else {
      //  prints.infofee_flag=0;
      //}
      savePrinter.getSavePrint(JSON.stringify(prints));
      $scope.$on('SavePrint.Updated', function() {
        var result=savePrinter.getResult();
        if (result.success==true){
          $ionicLoading.show({
            noBackdrop: true,
            template: result.msg,
            duration: 1500
          });
          $state.go('tab.person');
        }
      });
    };
    //添加打印机
    $scope.scanBluetooth=function(){
      $cordovaHdoitBle.scan();
    };
    $("#Bluetooth").val('未连接蓝牙设备');
    function getBleName(){
      //蓝牙设备名称
      $cordovaHdoitBle.bluetoothName(function(success){
        if(success!=null){
          $("#Bluetooth").val(success+'已连接');
        }
        else {
          $("#Bluetooth").val('未连接蓝牙设备');
        }
      },function(err){
        if(err!=null){
          $("#Bluetooth").val(err);
        }
        else {
          $("#Bluetooth").val('未连接蓝牙设备');
        }
      });
    }
    window.setInterval(getBleName,100);

  })
  .controller('confirmPwdCtrl', function($scope,$state,$ionicLoading,Storage,$interval,Login) {
    $("#nextStep").attr("disabled", true);
    var loginMsg=Storage.get('user');
    $scope.confirmPwd={
      username:loginMsg.username,
      password:'',
      uuid:loginMsg.uuid,
      key:''
    };
    $scope.changePwNum=function(){
      if($scope.confirmPwd.password!=''){
        $("#nextStep").attr("disabled", false);
      }
      else {
        $("#nextStep").attr("disabled", true);
      }
    };
    $scope.nextStep=function(){
      Login.getLogin(JSON.stringify($scope.confirmPwd));
      $scope.$on('Login.Updated', function() {
        var result = Login.getResult();
        if (result.success==true){
          $state.go('newPw');
        }else {
          $ionicLoading.show({
            noBackdrop: true,
            template: "密码错误",
            duration: 1500
          });
        }
      });
    };
  })
  .controller('changePwdCtrl', function($scope,$state,$ionicLoading,Storage,ChangePwd) {
    $("#changePw").attr("disabled", true);
    var loginMsg=Storage.get('user');
    $scope.changePwd={
      username:loginMsg.username,
      password:'',
      toPassword:'',
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    $scope.changePwNum=function(){
      if($scope.changePwd.password!=''&&$scope.changePwd.toPassword){
        $("#changePw").attr("disabled", false);
      }
      else {
        $("#changePw").attr("disabled", true);
      }
    };
    $scope.changePw=function(){
      if ($scope.changePwd.password==$scope.changePwd.toPassword){
        ChangePwd.getChangePwd(JSON.stringify($scope.changePwd));
      } else {
        $ionicLoading.show({
          noBackdrop: true,
          template: "密码不一致",
          duration: 1500
        });
      }
    };
    $scope.$on('ChangePwd.Updated', function() {
      var result=ChangePwd.getResult();
      if (result.success==true){
        $ionicLoading.show({
          noBackdrop: true,
          template: result.msg,
          duration: 1500
        });
        Storage.set('isLogin',0);
        Storage.remove('loginResult');
        $state.go('login');
      }else {
        $ionicLoading.show({
          noBackdrop: true,
          template: result.msg,
          duration: 1500
        });
      }
    });
  })
  .controller('feedbackCtrl', function($scope,$state,$ionicLoading,Storage,$ionicPopup,$ionicHistory) {
    var userMsg=Storage.get('loginResult');

    $scope.submitOpinion=function(){
      $ionicLoading.show({
        noBackdrop: true,
        template: "提交成功",
        duration: 1500
      });
      $state.go('tab.person');
    };
    //退出登录
    $scope.exitLogin=function(){
      var confirmPopup = $ionicPopup.confirm({
        title:'退出当前账号',
        template: '您确定要退出吗？',
        okText:'确定',
        cancelText:'取消'
      });
      confirmPopup.then(function(res) {
        if(res){
          Storage.set('isLogin',0);
          Storage.remove('loginResult');
          $ionicHistory.clearCache();
          $ionicHistory.clearHistory();
          $state.go('login');
        }
        else {
          return false;
        }
      });
    };
  })
